import local_enum from "./selectdata/local_enum"
import string_reg from "./string_reg"
import tool from "./tool"
import net_url from "./net_url"
import scan_consume from "./scan_consume"


import axios from 'axios'
import store from "../store/index"
import moment from 'moment-mini-ts'
Array.prototype.contains = Array.prototype.includes


/**
 * 缓存应用常用 的业务数据
 * @param  {[type]} Vue [description]
 * @return {[type]}     [description]
 */
const install = function (Vue, options) {

  Vue.prototype.$reg = string_reg

  Vue.prototype.$localEnum = local_enum

  Vue.prototype.$tool = tool
  Vue.prototype.$url = net_url


  let numRegex = /^-?[0-9]+(.[0-9]+)?$/

  Vue.prototype.$isNumber = function (input) {
    return numRegex.test(input)
  }

  Vue.prototype.$defaultDescAttrs = {
    size: "default", direction: "vertical", column: window.innerWidth > 1024 ? 4 : 1, border: true,
    labelClassName: 'widthdiv4', contentClassName: 'widthdiv4'
  }
  Vue.prototype.$defaultDetailDescAttrs = {
    size: "default",
    column: window.innerWidth > 1024 ? 4 : 1,
    labelClassName: 'w_max_50', contentClassName: 'widthdiv4 bold',
  }
  Vue.prototype.$dialogDetailDescAttrs = {
    size: "default", column: window.innerWidth > 1024 ? 3 : 1,
    labelClassName: 'w_max_50', contentClassName: 'widthdiv3 bold',
  }
  //常用标准校验规则
  Vue.prototype.$ruleStandard = function ({ v, cb, type, required, min, max }) {
    if (required && !v && !_.isNumber(v)) {
      cb(this.$tt('tip_can_no_empty'))
      return false
    }
    if (type === 'money' || type === 'ratio') {
      if ((v || _.isNumber(v)) && !this.$reg.DigitNumber(v, 2, 9)) {
        cb(this.$tt("tip_only_digit_int_length", { digit: 2, int: 9 }))
        return false
      }
    } else if (type === 'weight') {
      if ((v || _.isNumber(v)) && !this.$reg.DigitNumber(v, 3, 9)) {
        cb(this.$tt("tip_only_digit_int_length", { digit: 3, int: 9 }))
        return false
      }
    } else if (type === 'dimen') {
      if ((v || _.isNumber(v)) && !this.$reg.DigitNumber(v, 2, 9)) {
        cb(this.$tt("tip_only_digit_int_length", { digit: 2, int: 9 }))
        return false
      }
    } else if (type === 'volume') {
      if ((v || _.isNumber(v)) && !this.$reg.DigitNumber(v, 8, 9)) {
        cb(this.$tt("tip_only_digit_int_length", { digit: 8, int: 9 }))
        return false
      }
    }
    if (min || _.isNumber(min)) {
      if (Number(v) < Number(min)) {
        return false
      }
    }
    return true
  }

  Vue.directive('loadingCommonStyle', {
    bind: function (el, binding, vnode) {
      el.setAttribute("element-loading-text", Vue.prototype.$tt('tip_loading'));
      el.setAttribute("element-loading-spinner", "el-icon-loading");
    },
  })

  Vue.directive('stopRouteByVisible', {
    update: function (el, binding, vnode) {
      if (vnode.componentInstance && vnode.componentInstance.visible != undefined) {
        Vue.prototype.$store.commit('stopRoute', vnode.componentInstance.visible)
      }
    },
  })
  Vue.directive('loadMore', {
    bind(el, binding) {
      const dropdownDom = el.querySelector('.el-select-dropdown__wrap')
      // console.log(dropdownDom)
      dropdownDom.addEventListener('scroll', function (e) {
        // console.log(e, this.scrollHeight - this.scrollTop, this.clientHeight)
        const condition = this.scrollHeight - this.scrollTop <= this.clientHeight + 20
        if (condition) {
          binding.value && binding.value()
        }
      })
    },
  })

  //统一化表单校验错误提示方法

  Vue.prototype.$formRulesValidate = function ({ formRef, rules, success, props, }) {
    const validateCall = (errorObj) => {
      if (_.isEmpty(errorObj)) {
        success()
      } else {
        let errorMsg = `<strong><span style='line-height: 20px;'">${Vue.prototype.$tt('form_validate_error')}</span></strong>`
        if (rules) {
          _.forOwn(errorObj, (v, k) => {
            errorMsg += v.map(it => {
              let label = null
              if (rules[it.field]) {
                if (rules[it.field] instanceof Array && rules[it.field].some(it => it.label)) {
                  label = _.find(rules[it.field], it => it.label).label
                } else {
                  label = rules[it.field].label
                }
              }
              if (label) {
                const errorKey = Vue.prototype.$tt(label)
                return `<br/><span style='line-height: 20px;'">${errorKey} : ${it.message}</span>`
              }
              return null
            }).filter(it => it).join(";")
          })
        }
        Vue.prototype.$message.error({
          dangerouslyUseHTMLString: true,
          duration: 6000,
          showClose: true,
          message: `<div>${errorMsg}</div>`,
        })
        return false;
      }
    }
    // console.log( formRef, rules, success, props)
    if (!_.isEmpty(props)) {
      let errorObj = {}
      formRef.validateField(props, (errorMsg, errObj,) => {
        Object.assign(errorObj, errObj)
      });
      validateCall(errorObj)
    } else {
      formRef.validate((valid, errorObj,) => {

        validateCall(errorObj)
      });
    }

  }
  const color_map = {
    s: "color_success",
    w: "color_warning",
    d: "color_danger",

  }
  Vue.prototype.$renderText = function (h, value, option) {
    if (!option) option = {}
    let valueClass = option.valueClass ? option.valueClass : ""
    if (_.isObject(value)) {
      if (value.column && value.row) {
        value = value.row[value.column.property]
      } else if (value.data && value.item) {
        value = value.data[value.item.key]
      }
    }
    if (_.isEmpty(value)) {
      value = null
    }

    if (option.valueClassMap && option.valueClassMap[value]) {
      valueClass = option.valueClassMap[value]
    } else if (option.enum == "YesOrNoEnum") {
      valueClass = value == "Y" ? (option.reverse ? color_map.d : color_map.s) : (option.reverse ? color_map.s : color_map.d)
    } else if (option.enum == "YesOrNoOppositeEnum") {
      valueClass = value == "Y" ? (option.reverse ? color_map.s : color_map.d) : (option.reverse ? color_map.d : color_map.s)
    } else if (option.enum == "IsAvailableStatusEnum") {
      valueClass = value == "ENABLE" ? (option.reverse ? color_map.d : color_map.s) : (option.reverse ? color_map.s : color_map.d)
    }
    const tempClass = option.tempClass ? option.tempClass : "color_info"
    const tempText = option.tempText ? option.tempText : "data_temp_none"
    const showValue = option.showValue ? option.showValue : (option.enum ? Vue.prototype.$enumShow(value, option.enum) : value)
    return h("span", {
      class: value ? valueClass : tempClass,
    }, [
      value ? showValue : this.$t(tempText)
    ])
  }
  //预计统一处理重量与体积精度
  Vue.prototype.$toFixedQuick = {
    DimenPrecision: 2,
    Dimen: function (value,) { return Vue.prototype.$math_toFixed(value, Vue.prototype.$toFixedQuick.DimenPrecision) },
    WeightPrecision: 3,
    Weight: function (value,) { return Vue.prototype.$math_toFixed(value, Vue.prototype.$toFixedQuick.WeightPrecision) },
    VolumePrecision: 8,
    Volume: function (value,) { return Vue.prototype.$math_toFixed(value, Vue.prototype.$toFixedQuick.VolumePrecision) },
    DensityPrecision: 8,
    Density: function (value,) { return Vue.prototype.$math_toFixed(value, Vue.prototype.$toFixedQuick.DensityPrecision) },
  }

  //增加单位后缀
  Vue.prototype.$addUnit = function (value, unit) {
    if (_.isEmpty(value)) return ""
    return `${value} ${unit}`
  }
  Vue.prototype.$addUnitQuick = {
    DimenUnit: 'cm',
    Dimen: function (value, unit) {
      if (_.isNil(value) && !_.isNumber(value)) return ""
      if (!unit) unit = Vue.prototype.$addUnitQuick.DimenUnit
      return Vue.prototype.$addUnit(Vue.prototype.$toFixedQuick.Dimen(value), unit)
    },
    WeightUnit: 'kg',
    Weight: function (value, unit) {
      if (_.isNil(value) && !_.isNumber(value)) return ""
      if (!unit) unit = Vue.prototype.$addUnitQuick.WeightUnit

      return Vue.prototype.$addUnit(Vue.prototype.$toFixedQuick.Weight(value), unit)
    },
    VolumeUnit: 'm³',
    Volume: function (value, unit) {
      if (_.isNil(value) && !_.isNumber(value)) return ""
      if (!unit) unit = Vue.prototype.$addUnitQuick.VolumeUnit
      return Vue.prototype.$addUnit(Vue.prototype.$toFixedQuick.Volume(value), unit)
    },
    DensityUnit: 'kg/m³',
    Density: function (value, unit) {
      if (_.isNil(value) && !_.isNumber(value)) return ""
      if (!unit) unit = Vue.prototype.$addUnitQuick.DensityUnit
      return Vue.prototype.$addUnit(Vue.prototype.$toFixedQuick.Density(value), unit)
    },
  }

  //增加单位后缀
  Vue.prototype.$addUnit = function (value, unit) {
    if (_.isEmpty(value)) return ""
    return `${value} ${unit}`
  }
  Vue.prototype.$addUnitQuick = {
    DimenUnit: 'cm',
    Dimen: function (value, unit) {
      if (_.isNil(value) && !_.isNumber(value)) return ""
      if (!unit) unit = Vue.prototype.$addUnitQuick.DimenUnit
      return Vue.prototype.$addUnit(Vue.prototype.$toFixedQuick.Dimen(value), unit)
    },
    WeightUnit: 'kg',
    Weight: function (value, unit) {
      if (_.isNil(value) && !_.isNumber(value)) return ""
      if (!unit) unit = Vue.prototype.$addUnitQuick.WeightUnit

      return Vue.prototype.$addUnit(Vue.prototype.$toFixedQuick.Weight(value), unit)
    },
    VolumeUnit: 'm³',
    Volume: function (value, unit) {
      if (_.isNil(value) && !_.isNumber(value)) return ""
      if (!unit) unit = Vue.prototype.$addUnitQuick.VolumeUnit
      return Vue.prototype.$addUnit(Vue.prototype.$toFixedQuick.Volume(value), unit)
    },
    DensityUnit: 'kg/m³',
    Density: function (value, unit) {
      if (_.isNil(value) && !_.isNumber(value)) return ""
      if (!unit) unit = Vue.prototype.$addUnitQuick.DensityUnit
      return Vue.prototype.$addUnit(Vue.prototype.$toFixedQuick.Density(value), unit)
    },
  }
  Vue.prototype.$formatNameCode = function (name, code, tempTip) {

    if (tempTip === undefined) tempTip = ''
    if (_.isEmpty(name) && _.isEmpty(code)) return tempTip ? Vue.prototype.$tt(tempTip) : tempTip
    let value = []
    if (!_.isEmpty(name)) value.push(name)
    if (!_.isEmpty(code)) {
      value.push(`[${code}]`)
    }
    return value.join(' ')
  }
  Vue.prototype.$formatDigit = function (data, diaitNumber = 3) {

    if (data || data == 0) {
      const list = _.split(data, '.')
      if (list.length == 2) {
        return list[0] + '.' + _.padEnd(list[1], diaitNumber, '0')
      } else {
        return list[0] + '.' + _.padEnd('', diaitNumber, '0')
      }
    } else {
      return ""
    }
  };
  //利用字符串正则替换变更变量
  Vue.prototype.$formatReg = function (text, option) {
    let t_text = text
    if (option instanceof Object) {
      _.forOwn(option, (value, key) => {
        t_text = t_text.replace(new RegExp(`\\{(\\s*?)${key}(\\s*?)\\}`), value)
      });
    }
    return t_text
  }


  Vue.prototype.$date_range_shortcuts = function () {

    const list = [
      {
        text: Vue.prototype.$tt('label_last_three_month'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(3, 'months').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
      {
        text: Vue.prototype.$tt('label_last_two_month'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(2, 'months').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
      {
        text: Vue.prototype.$tt('label_last_one_month'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(1, 'months').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
      {
        text: Vue.prototype.$tt('label_last_three_week'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(3, 'weeks').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
      {
        text: Vue.prototype.$tt('label_last_two_week'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(2, 'weeks').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
      {
        text: Vue.prototype.$tt('label_last_one_week'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(1, 'weeks').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
      {
        text: Vue.prototype.$tt('label_last_five_day'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(5, 'days').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
      {
        text: Vue.prototype.$tt('label_last_three_day'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(3, 'days').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
      {
        text: Vue.prototype.$tt('label_last_one_day'),
        onClick(picker) {
          picker.$emit('pick', [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(1, 'days').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]);
        }
      },
    ]
    return list
  }

  //element指令拓展
  Vue.prototype.$msgbox_table = function ({ note, tableProp }, option) {
    const h = this.$createElement;
    let notesNote = _.isString(note) ? [h('div', null, note)] : note.map(it => h('div', null, it))
    let config = Object.assign({
      title: Vue.prototype.$tt('label_tip'),
      message: h('div', null, [
        ...notesNote,
        // h('div', null, note),
        // h('div', null, note2),
        h('ex_super_table', {
          props: tableProp,
        }, []),
      ]),
    }, option,)
    return this.$msgbox(config)
  }
  Vue.prototype.$msgbox_filelist = function (files, option) {

    const h = this.$createElement;
    let child = [this.$tt('label_empty_file_list')]
    if (files.length > 0) {
      child = files.map(it => {
        return (<div class="mg_v1">
          <a class="a_file_link" href={this.$ex_default_download_url + it.filePath} target="_blank" download={it.fileName}>
            <i class="el-icon-download el-icon--left" />
            {it.fileName}
          </a>
        </div>)
      })
    }
    option = Object.assign({}, {
      message: h('div', null, child),
      showConfirmButton: false,

    }, option,)


    this.$msgbox(option).then(() => {

    }).catch(() => {

    });
  }


  //日期格式化 (YY-MM-DD)
  Vue.prototype.$dateFormatDate = function (mill, format) {
    let fmt = 'YYYY-MM-DD'
    if (format) {
      fmt = format
    }
    return Vue.prototype.$dateFormat(mill, fmt)
  }
  Vue.prototype.$dateFormatTime = function (mill, format) {
    let fmt = 'YYYY-MM-DD HH:mm:ss'
    if (format) {
      fmt = format
    }
    return Vue.prototype.$dateFormat(mill, fmt)
  }
  //日期格式化
  Vue.prototype.$dateFormat = function (mill, format) {
    let t = Number.parseInt(mill)
    if (Number.isNaN(t)) return ""
    if (!t) return ""
    let fmt = 'YYYY-MM-DD HH:mm'
    if (format) {
      fmt = format
    }
    return moment(t).format(fmt)
  }

  try {

    Vue.prototype.$enumOptions = __JAVA_ENUM_OPTIONS__
  } catch (e) {
    Vue.prototype.$enumOptions = {}
    alert(Vue.prototype.$tt('tip_remote_enumeration_class_initialization_failed'))
  }
  Vue.prototype.$queryObj = function (str) {
    if (_.startsWith(str, "?")) {
      str = str.substring(1)
    }
    let keyvalues = _.split(str, '&')
    let obj = {}
    keyvalues.forEach(it => {
      let kvlist = _.split(it, '=')
      if (kvlist.length > 1) {
        obj[kvlist[0]] = kvlist[1]
      }
    })
    return obj
  }

  Vue.prototype.$queryStr = function (obj) {
    if (obj instanceof Object) return "?" + _.join(_.toPairs(obj).map(it => `${it[0]}=${it[1]}`), '&')
    return String(obj)
  }

  Vue.prototype.$enumShow = function (value, enumType) {
    if (!value) {
      return ''
    }
    if (typeof value == 'string') {
      return Vue.prototype.$tt(value ? (enumType + '__' + value) : '')
    }
    else {
      let arr = []
      value.forEach(ee => {
        arr.push(
          Vue.prototype.$tt(ee ? (enumType + '__' + ee) : '')
        )
      })
      return arr.join(', ')
    }
  }
  Vue.directive('auth', {
    bind(el, binding) {
      const code = binding.value
      if (code) {
        if (!Vue.prototype.$default_auth_check(code)) {
          el.remove()
        }
      }
    },
    update(el, binding) {
      const code = binding.value
      if (code) {
        if (!Vue.prototype.$default_auth_check(code)) {
          el.remove()
        }
      }
    },
  })
  Vue.prototype.$default_auth_check = function (code) {
    const _user = __LONG_USER__
    if (_user) {
      if (_user.isSuperAdmin()) {
        return true
      } else if (_user.btnCodes && _user.btnCodes.includes(code)) {
        return true
      } else if (_user.menus && _user.menus.includes(code)) {
        return true
      } else {
        return false
      }
    }
    return true
  }
  Vue.prototype.$auth = function (key) {
    const login_user = __LONG_USER__
    if (login_user.isSuperAdmin()) {
      return true
    } else {
      return login_user.btnCodes.includes(key)
    }
  }

  Vue.prototype.$noFunction = function () {
    Vue.prototype.$message.warning(Vue.prototype.$tt('tip_function_not_implemented'))
  }
  const clickFastCache = {
    lastDate: 0
  }
  Vue.prototype.$clickFast = function (key, tip,) {
    let now = new Date().getTime()
    let last = clickFastCache[key ? key : 'lastDate']
    if (last == undefined) last = 0
    if (now - last >= 800) {
      clickFastCache[key ? key : 'lastDate'] = now
      return false
    } else {
      if (!!tip) Vue.prototype.$message.warning(Vue.prototype.$tt('tip_please_no_operate_fast'))
      return true
    }
  }

  //用于扫描消费组件堆栈

  Vue.prototype.$ScanConsume = scan_consume


  //用于底部网络同步请求
  const NetChace = {}
  Vue.prototype.$NetCacheStack = {
    keyBuild: function (url, data) {
      return url + Vue.prototype.$queryStr(data)
    },
    get: function (url, data) {
      const key = Vue.prototype.$NetCacheStack.keyBuild(url, data)
      if (!NetChace[key]) {
        NetChace[key] = []
      }
      return NetChace[key]
    },

    delete: function (url, data) {
      const key = Vue.prototype.$NetCacheStack.keyBuild(url, data)
      delete NetChace[key]
    },
  }

  //增加便捷事件链接
  Vue.prototype.$emitPage = function (key, ...args) {
    this.$bus.$emit(key, ...args)
  }
  Vue.prototype.$refreshStoreCommonDataGroup = function (group,) {
    this.$store.dispatch('refreshCommonData', { group })
  }
  //增加统一网络请求 缓存机制
  Vue.prototype.$ajaxCache = function (params, hasCacheCallback) {
    let { url, data, success, complete, cache, ...other } = params
    let key = url
    let key2 = JSON.stringify(data)

    if (cache != false) {
      if (this.$cache.has2(key, key2)) {
        let res = _.cloneDeep(this.$cache.get2(key, key2))
        if (hasCacheCallback) hasCacheCallback(res)

        if (success) success(res)
        if (complete) complete()
        return
      }
    }
    this.$ajax({
      url, data, ...other, complete,
      success: (res) => {
        if (cache != false) {
          this.$cache.set2(key, key2, res)
        }
        if (success) success(res)
      },
    })
  }






  //获取文档列表
  Vue.prototype.$getAllDocs = function (callback) {
    Vue.prototype.$ajax({
      url: '/open-api/open/AutoDocumentRpc/getDocs.json',
      success: function (res) {
        callback(res.data)
      }
    })
  }

  Vue.prototype.$storeUrlCache = function ({ url, param, success, netConfig }) {

    const key = this.$queryStr(param)
    const cache = store.state.commonMapCache[url] ?
      store.state.commonMapCache[url][key] : null
    if (cache) {
      success(cache)
    } else {
      this.$ajax(Object.assign({
        url, data: param,
        success: function (res) {
          if (res.data && res.data.rows) {
            store.commit("pushCommonData", {
              group: url,
              key: key,
              data: res.data.rows
            })
            success(res.data.rows)
          }

        }
      }, netConfig))
    }

  }
  Vue.prototype.$functionCommon = function ({ url, file, type, data, success, commonType },) {
    if (!type) type = 'json'
    const call = (res) => {
      if (success) {
        success()
      }
      let tip = "tip_exporting_confirm_goto_recode_list"
      let manage_page = "export_manage"
      let system = 'oms'

      if (commonType == 'import') {
        tip = "tip_importing_confirm_goto_recode_list"
        manage_page = "import_manage"
      }
      if (this.$loginUser.isWmsSystem) {
        system = 'wms'
      }
      this.$confirm(this.$tt(tip), this.$tt('label_tip'), {
        type: 'success'
      }).then(() => {
        this.$emitPage(`${system}>${manage_page}`, 'reload')
        this.$router.push({
          path: `/page/${system}/report/${manage_page}`,
        });
      }).catch(() => {
      });
    }
    if (commonType == 'import') {
      this.$uploadFile({
        loading: true,
        url,
        file,
        success: (res) => {
          call(res)
        }
      })
    } else {
      this.$ajax({
        url,
        method: 'post',
        type,
        loading: true,
        data: Object.assign({}, data),
        success: (res) => {
          call(res)
        }
      })
    }

  }



  /**
   * 将文本内容拷贝至剪切板
   * @param  {[type]} content [文本内容]
   * @param  {[type]} msg     [复制成功后的提示]
   */
  Vue.prototype.$copyToClip = async function (content, msg, nodeId) {

    let ok = false


    if (navigator.clipboard && window.isSecureContext) {
      try {
        await navigator.clipboard.writeText(content);
        ok = true
      } catch (err) { }
    }
    if (!ok) {
      let node = document.body
      if (nodeId) {
        node = document.querySelector("#"+nodeId)
      }
      let aux = document.createElement('input')
      aux.setAttribute('value', content)
      node.appendChild(aux)
      aux.select()
      document.execCommand('copy')
      node.removeChild(aux)
    }


    if (msg) {
      Vue.prototype.$message({
        type: 'success',
        message: msg
      })
    }
  }


  const dpi = {}

  if (window.screen.deviceXDPI) {
    dpi.dpiX = window.screen.deviceXDPI;
    dpi.dpiY = window.screen.deviceYDPI;
  } else {
    const tmpNode = document.createElement("div");
    tmpNode.style.cssText = "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
    document.body.appendChild(tmpNode);
    dpi.dpiX = parseInt(tmpNode.offsetWidth);
    dpi.dpiY = parseInt(tmpNode.offsetHeight);
    tmpNode.parentNode.removeChild(tmpNode);
  }


  /**
     * px转换为mm
     * @param value
     * @returns {number}
     */
  dpi.px2mm = function (value) {
    var inch = value / dpi.dpiX;
    var c_value = inch * 25.4;
    return c_value;
  };
  /**
      * px转换为cm
      * @param value
      * @returns {number}
      */
  dpi.px2cm = function (value) {
    var inch = value / dpi.dpiX;
    var c_value = inch * 2.54;
    return c_value;
  };
  /**
   * mm转换为px
   * @param value
   * @returns {number}
   */
  dpi.mm2px = function (value) {
    var inch = value / 25.4;
    var c_value = inch * dpi.dpiX;
    return c_value;
  }
  /**
   * cm转换为px
   * @param value
   * @returns {number}
   */
  dpi.cm2px = function (value) {
    var inch = value / 2.54;
    var c_value = inch * dpi.dpiX;
    return c_value;
  }
  dpi.cm2mm = function (value) {
    return value * 10;
  }
  dpi.mm2cm = function (value) {
    return value / 10;
  }
  dpi.convert = function (value, oldUnit, newUnit) {
    if (!value) return value
    if (oldUnit == newUnit) return value
    if (newUnit == 'px') {
      return Number(dpi[`${oldUnit}2${newUnit}`](value).toFixed(0));
    } else {
      return Number(dpi[`${oldUnit}2${newUnit}`](value).toFixed(2));

    }
  }


  Vue.prototype.$dpi = dpi

  Vue.prototype.$downloadBuffer = function ({ buffer, type, filename }) {
    let blob = new Blob([buffer], { type: type });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(a.href);

  }

  Vue.prototype.$downloadFile = function (cfg) {
    if (cfg.window) {
      let windowUrl = cfg.oss ? (Vue.prototype.$ex_default_download_url + cfg.url) : cfg.url
      if (cfg.oss) {
        cfg.data = Object.assign({ attname: cfg.url.substring(cfg.url.lastIndexOf('/') + 1) }, cfg.data)
      }
      if (!_.isEmpty(cfg.data)) {
        windowUrl += ("?" + this.$qs.stringify(cfg.data))
      }
      window.open(windowUrl)

      return
    } else if (cfg.a) {
      let windowUrl = cfg.oss ? (Vue.prototype.$ex_default_download_url + cfg.url) : cfg.url
      const a = document.createElement('a')
      if (cfg.target) a.target = cfg.target
      a.href = windowUrl
      document.body.appendChild(a);
      a.click()
      document.body.removeChild(a);
      return
    }

    let loading = null
    if (cfg.loading) {
      let _loadObj = {
        lock: true,
        text: Vue.prototype.$tt('tip_loading'),
      }
      if (cfg.loading instanceof String) {
        _loadObj.text = cfg.loading
      } else if (cfg.loading instanceof Object) {
        Object.assign(_loadObj, cfg.loading)
      }
      loading = this.$loading(_loadObj);
    }
    const headers = Object.assign({}, cfg.headers, cfg.type == 'json' ? { 'content-type': 'application/json' } : {})
    const net_obj = {
      method: cfg.method || 'post',
      responseType: 'blob',
      url: cfg.oss ? (Vue.prototype.$ex_default_download_url + cfg.url) : cfg.url,
      headers,
    }
    if (cfg.data) {
      if (cfg.type && cfg.type === 'json') {
        net_obj.data = JSON.stringify(cfg.data)
      } else {
        net_obj.data = this.$qs.stringify(cfg.data)
      }
    }

    axios(net_obj).then((response) => {
      if (loading) loading.close();
      if (response.status == 200) {
        if (response.headers && response.headers['content-type'] &&
          response.headers['content-type'].includes('application/json')) {
          const reader = new FileReader()
          reader.onload = () => {
            const json_result = JSON.parse(reader.result)
            if (cfg.fail) {
              cfg.fail(json_result)
            } else {
              this.$message.error(json_result.message || this.$tt('label_download_fail'))
            }
          }
          reader.readAsText(response.data, "utf-8")
          return
        }
        if (response.data instanceof Blob) {
          const blob = response.data
          let fileName = Math.random()
          let disposition = response.headers['content-disposition']
          if (disposition) {
            const _fileheader = _.split(disposition, ';')
            const _filenameKV = _.find(_fileheader, it => _.startsWith(it.replace(/^\s*|\s*$/g, ""), 'filename'))
            if (_filenameKV) {
              const _filenameList = _.split(_filenameKV, '=')
              if (_filenameList.length == 2) {
                fileName = decodeURIComponent(_filenameList[1]);
              }
            }
          } else if (cfg.oss) {
            fileName = cfg.url.substring(cfg.url.lastIndexOf('/') + 1);
          } else {
            const ext = Vue.prototype.$reg.FileExt(cfg.url);
            if (ext) {
              fileName = fileName + "." + ext
            }
          }


          if (cfg.download != false) {
            const url = window.URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            if (cfg.target) a.target = cfg.target

            a.download = fileName
            a.click()
            window.URL.revokeObjectURL(url)
          }
          if (cfg.success) {
            cfg.success(blob, fileName)
          } else {
            this.$message.success(this.$tt('label_download_success'))
          }
          return
        }
      }
      if (cfg.fail) {
        cfg.fail(null)
      } else {
        this.$message.error(this.$tt('label_download_fail'))
      }
    }, err => {
      if (loading) loading.close();
      if (cfg.fail) {
        cfg.fail(null, err)
      } else {
        this.$message.error(this.$tt('label_download_fail'))
      }
    })


  }



  //文件快捷上传方法
  Vue.prototype.$uploadFile = function (cfg) {
    let loading = null
    if (cfg.loading) {
      let _loadObj = {
        lock: true,
        text: Vue.prototype.$tt('tip_submiting'),
      }
      if (cfg.loading instanceof String) {
        _loadObj.text = cfg.loading
      } else if (cfg.loading instanceof Object) {
        Object.assign(_loadObj, cfg.loading)
      }
      loading = this.$loading(_loadObj);
    }
    const formData = new FormData();
    formData.append("file", cfg.file);
    if (cfg.data) {
      _.forOwn(cfg.data, (v, k) => {
        formData.append(k, v);
      })
    }
    axios({
      method: 'post', // default
      url: cfg.url,
      data: formData,
      headers: Object.assign({ 'Content-type': 'multipart/form-data' }, cfg.headers)
    }).then(response => {
      if (loading) loading.close();
      if (response.data.code == 0) {
        if (cfg.success) {
          cfg.success(response.data)
        } else {
          this.$message.success(this.$tt('label_upload_success'));
        }
      } else {
        this.$message.error(response.data.message || this.$tt('label_upload_fail'));
      }
    }, err => {
      if (loading) loading.close();
      this.$message.error(this.$tt('label_upload_error'))
    })
  }


  let __CHAR_ARRAYS__ = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  Vue.prototype.$uuid = function () {
    let len = 32
    let output = ''
    for (let i = 0; i < len; i++) {
      let index = parseInt(Math.random() * __CHAR_ARRAYS__.length)
      output += __CHAR_ARRAYS__.substring(index, index + 1)
    }

    return output;
  }

  // 初始化全局电子称对象
  Vue.prototype.$autoWeightGlobal = {
    serialObj: null,
    stableValue: '',  // 稳定值
    value: '', // 当前取值
    status: 'init', // 'init  / connected',  // 电子称的状态
    autoWeightObjects: {                 //  缓存对象
      //'instanceId': 'autoWeight object'
    }
  }


}

export default {
  install
}
